package com.wuwei.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wuwei.common.constant.ProductConstant;
import com.wuwei.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.wuwei.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.wuwei.gulimall.product.entity.AttrGroupEntity;
import com.wuwei.gulimall.product.entity.CategoryEntity;
import com.wuwei.gulimall.product.service.AttrAttrgroupRelationService;
import com.wuwei.gulimall.product.service.AttrGroupService;
import com.wuwei.gulimall.product.service.CategoryService;
import com.wuwei.gulimall.product.vo.AttrGroupRelationVo;
import com.wuwei.gulimall.product.vo.AttrRespVo;
import com.wuwei.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.common.utils.PageUtils;
import com.wuwei.common.utils.Query;

import com.wuwei.gulimall.product.dao.AttrDao;
import com.wuwei.gulimall.product.entity.AttrEntity;
import com.wuwei.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr,entity);
        //保存基本数据
        this.save(entity);
        //保存关联关系
        if (attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrGroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrGroupRelationEntity.setAttrId(entity.getAttrId());
            attrGroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrGroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>();
        wrapper.eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(attrType)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (catelogId!=0){
            wrapper.eq(AttrEntity::getCatelogId,catelogId);
        }
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(a->{
                a.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map(AttrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(AttrEntity, attrRespVo);
            CategoryEntity categoryEntity = categoryService.getById(AttrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            Long attrId = AttrEntity.getAttrId();
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrId).isNotNull(AttrAttrgroupRelationEntity::getAttrGroupId);
            AttrAttrgroupRelationEntity entity = attrAttrgroupRelationService.getOne(queryWrapper);
            if (entity != null) {
                Long attrGroupId = entity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
                if (attrGroupEntity != null) {
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    attrRespVo.setGroupName(attrGroupName);
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrEntity getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            Long catelogId = attrEntity.getCatelogId();
            //拿到分类完整路径
            Long[] parentPath = categoryService.getParentPath(catelogId);
            attrRespVo.setCatelogPath(parentPath);
        }
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //更新属性信息
        this.updateById(attrEntity);
        //更新分组信息
        Long attrGroupId = attr.getAttrGroupId();
        int count = attrAttrgroupRelationService.count(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
        attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
        //大于0表明做的是修改
        if (count>0){
            attrAttrgroupRelationService.update(attrAttrgroupRelationEntity,
                    new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                            .eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId())
            );
            return;
        }
        //否则进行新增操作
        attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
    }


    /**
     * 获取属性分组的关联的所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId));
        List<Long> attrIdList = attrgroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (attrIdList.size()==0||attrIdList==null){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIdList);
        return (List<AttrEntity>)attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVo) {
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.stream(attrGroupRelationVo).map(a -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(a, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.batchDeleteAttrGroupRelation(relationEntityList);
    }

    /**
     * 删除属性同时解除属性和分组的关系
     * @param attrIds
     */
    @Override
    @Transactional
    public void removeAndUnRelated(List<Long> attrIds) {
        this.removeByIds(attrIds);
        //解除属性和分组的关系
        attrAttrgroupRelationDao.batchAttrIdDelete(attrIds);
    }


}
